//
// Created by Toosan on 2022/4/23.
//

#include "../day08/head/main2_head.h"

class Cat {
private:
    int age{};
    char *name = static_cast<char *>(malloc(sizeof(char) * 10));
public:
    Cat() {

    }

    int getAge() {
        return this->age;
    }

    void setAge(int age_) {
        this->age = age_;
    }

    char *getName() {
        return this->name;
    }

    void setName(char *name_) {
        this->name = (char *) (malloc(sizeof(char *) * 10));
        strcpy(this->name, name_);
    }

    Cat(const Cat &cat) {
        cout << "free cat" << endl;
        this->age = cat.age;
        this->name = (char *) (malloc(sizeof(char *) * 10));
        strcpy(this->name, cat.name);
    }

    ~Cat() {
        free(this->name);
        this->name = NULL;
    }
    // 把changeAge声明为友元函数，那么该函数就可以访问此类中的所有私有成员了
    friend void changeAge(Cat *cat, int age);
};

void changeAge(Cat *cat, int age) {
    cout << "changeAge   " << cat << endl;
//    cat->setAge(age);
    /**
     * 私有成员变量是不能直接获取到的
     * 如果想要一个函数访问某个类的私有成员，在该类中，把这个函数声明为友元函数就可以访问了
     */
//    cat->age = age;
    cat->age = age;

}

void showAge(Cat cat) {
    cout << cat.getAge() << endl;
    cout << "showAge   " << &cat << endl;
}

/**
 * 友元函数学习
 * @return 0
 */
int main_day10_2() {
    Cat cat;
    cout << "main   " << &cat << endl;
    cat.setAge(10);
    cat.setName("Tikey");
    changeAge(&cat, 20);
    showAge(cat);
    showAge(cat);
    return 0;
}